package config

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"path"
)

// make a copy of this file, rename to settings.go
// then set the correct value for these follow variables
var (
	PublicDirectory        = "D:/Ocean/gserver/src/wserver/public"
	TemplateDirectory      = "D:/Ocean/gserver/src/wserver/templates"
	PublicStorageDirectory = "/home/happy/Documents"
	WebPort                = 3000
	OServerPort            = 17272
	UServerPort            = 4001
	LogFile                = ""
	Daemon                 = ""
)

func ParseConfigFile(filepath string) bool {
	type Params struct {
		WebRoot                string `json:"web_root"`
		PublicStorageDirectory string `json:"pub_storage"`
		WebPort                int    `json:"web_port"`
		OServerPort            int    `json:"oserver_port"`
		UServerPort            int    `json:"userver_port"`
		LogFile                string `json:"log_file"`
		Daemon                 string `json:"daemon"`
	}

	data, err := ioutil.ReadFile(filepath)
	if err != nil {
		log.Println("read configure file error:", err)
		return false
	}

	var params = &Params{}
	err = json.Unmarshal(data, params)
	if err != nil {
		log.Println("json un-marshal error:", err)
		return false
	}

	log.Println("-------------------Configure params are:-------------------")
	log.Println(params)

	if params.WebRoot != "" {
		PublicDirectory = path.Join(params.WebRoot, "public")
		TemplateDirectory = path.Join(params.WebRoot, "templates")
	}

	if params.PublicStorageDirectory != "" {
		PublicStorageDirectory = params.PublicStorageDirectory
	}

	if params.LogFile != "" {
		LogFile = params.LogFile
	}

	if params.Daemon != "" {
		Daemon = params.Daemon
	}

	return true
}
